<template>
  <el-dialog :title="!dataForm.id ? 'Add Role' : 'Edit Role'" :close-on-click-modal="false" :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="100px">
      <el-form-item label="Role Name" prop="name">
        <el-input v-model="dataForm.name" placeholder="Role Name"></el-input>
      </el-form-item>
      <el-form-item label="Alias" prop="alias">
        <el-input v-model="dataForm.alias" placeholder="Alias"></el-input>
      </el-form-item>
      <el-form-item size="mini" label="Permissons">
        <el-tree :data="menuList" :props="menuListTreeProps" node-key="id" ref="menuListTree" :default-expand-all="true" show-checkbox></el-tree>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">Cancel</el-button>
      <el-button type="primary" @click="dataFormSubmit()">OK</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { treeDataTranslate } from "@/utils";
import { mapMutations } from "vuex";
export default {
  data() {
    return {
      visible: false,
      menuList: [],
      menuListTreeProps: {
        label: "name",
        children: "children",
      },
      dataForm: {
        id: 0,
        name: "",
        alias: "",
      },
      dataRule: {
        name: [{ required: true, message: "Role Name is required", trigger: "blur" }],
        alias: [{ required: true, message: "Alias is required", trigger: "blur" }],
      },
      tempKey: -666666, // 临时key, 用于解决tree半选中状态项不能传给后台接口问题. # 待优化
    };
  },
  methods: {
    ...mapMutations("role", ["addOne", "updateOne"]),
    async init(id) {
      this.dataForm.id = id || 0;
      const { data } = await this.$http.get("/sysMenu/getList");
      this.menuList = treeDataTranslate(data, "id");
      this.visible = true;
      await this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        this.$refs.menuListTree.setCheckedKeys([]);
      });
      if (this.dataForm.id) {
        const { data } = await this.$http.get(`/sysRole/${this.dataForm.id}/detail`);
        this.dataForm.name = data.name;
        this.dataForm.alias = data.alias;
        var idx = data.menuIdList.indexOf(this.tempKey);
        if (idx !== -1) {
          data.menuIdList.splice(idx, data.menuIdList.length - idx);
        }
        this.$refs.menuListTree.setCheckedKeys(data.menuIdList);
      }
    },
    // 表单提交
    async formSubmitRequest(params) {
      if (params.id) {
        return await this.$http.post(`/sysRole/${params.id}/update`, params);
      } else {
        return await this.$http.post(`/sysRole/create`, params);
      }
    },
    dataFormSubmit() {
      this.$refs["dataForm"].validate(async valid => {
        if (valid) {
          const params = {
            id: this.dataForm.id,
            name: this.dataForm.name,
            alias: this.dataForm.alias,
            menuIdList: [].concat(this.$refs.menuListTree.getCheckedKeys(), [this.tempKey], this.$refs.menuListTree.getHalfCheckedKeys()),
          };
          const { code, msg } = await this.formSubmitRequest(params);
          if (code === 200) {
            if (this.dataForm.id) {
              this.updateOne(params);
            } else {
              this.addOne(params);
            }
            this.$message({
              message: "success",
              type: "success",
              duration: 1500,
              onClose: () => {
                this.visible = false;
                this.$emit("refreshDataList");
              },
            });
          } else {
            this.$message.error(msg);
          }
        }
      });
    },
  },
};
</script>
